package com.fzrskj.cloud.free.user.task;

import com.fzrskj.cloud.free.core.tool.CDateTimeTool;
import com.fzrskj.cloud.free.core.tool.CStrTool;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.dic.utils.DicParamUtils;
import com.fzrskj.cloud.free.sys.utils.SysRunTimeLogUtils;
import com.fzrskj.cloud.free.user.bean.UserCart;
import com.fzrskj.cloud.free.user.utils.UserCartUtils;
import com.fzrskj.cloud.free.user.utils.UserOrderUtils;
import com.fzrskj.cloud.free.user.utils.UserLogUtils;
import com.fzrskj.cloud.free.user.bean.UserOrder;
import ms.core.db.ConnectionContext;

import javax.servlet.ServletContext;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;

/**
 * 订单自动任务.
 * @author zj.
 */
public class UserOrderRecycleTask extends TimerTask{
	private ServletContext sc = null;
	private static boolean running=false;

	/**
	 * constructor method of CCoreTask
	 * @param sc sc.
	 */
	public UserOrderRecycleTask(ServletContext sc){
		this.sc = sc;
	}
	
	@Override
	public void run() {
		if (!running){
			try {
				running = true;
				sc.log("start running UserOrderRecycleTask...");
				doTask();
				running = false;
				sc.log("UserOrderRecycleTask runned.");
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				ConnectionContext.closeAllConnection();
			}
		}
	}

	/**
	 * 执行任务.
	 */
	private void doTask(){
		delNoPayOrder();
		delCartNoBuildOrder();
	}

	/**
	 * 删除到期未支付订单.
	 */
	private void delNoPayOrder(){
		DicParamUtils dpUtils = new DicParamUtils();
		UserOrderUtils uoUtils = new UserOrderUtils();

		try{
			//取系统配置未支付时间
			int day=0;
			CloudContextUtils.setAgentId(CloudContextUtils.DEF_AGENT_ID);
			String expiryDays = dpUtils.getParamValue("orderPayData", 1);
			if(CStrTool.isBlankStr(expiryDays)) {
				return;
			} else {
				day = CStrTool.strToIntDef(expiryDays, 0);
			}

			Date expiry= CDateTimeTool.dateAdd(new Date(), 0, 0, -day);
			String dateTime=CDateTimeTool.formatDateTime(expiry,"yyyy-MM-dd");
			List<UserOrder> list = uoUtils.queryExpireNoPayOrder(dateTime);
			if(list.size()==0) {
				return;
			}

			for(UserOrder uo:list){
				CloudContextUtils.setAgentId(CloudContextUtils.DEF_AGENT_ID);
				//删除到期未支付订单
				Map<String, Object> cdt = new HashMap<String, Object>();
				cdt.put("userId", uo.getUserId());
				cdt.put("orderId", uo.getOrderId());
				int ret=uoUtils.delUserOrder(cdt);
				if(ret>0){
					UserLogUtils.addLog(this, 1000, "delNoPayOrder", "系统自动任务：删除到期未支付订单，订单号【"+uo.getOrderId()+"】，生成订单时间【"+uo.getOrderDate()+"】");
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
			StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            SysRunTimeLogUtils.addLog(this, 1000, "delNoPayOrder", "删除未支付订单任务，异常=【"+e.getMessage()+"】");
		}
	}

	/**
	 * 删除购物车中未生成订单.
	 */
	private void delCartNoBuildOrder(){
		try{
			DicParamUtils dpUtils = new DicParamUtils();
			UserCartUtils ucUtils = new UserCartUtils();

			//取系统配置未生成订单时间
			int day=0;
			CloudContextUtils.setAgentId(CloudContextUtils.DEF_AGENT_ID);
			String expiryDays = dpUtils.getParamValue("orderCarData", 1);
			if(CStrTool.isBlankStr(expiryDays)) {
				return;
			} else {
				day = CStrTool.strToIntDef(expiryDays, 0);
			}

			Date expiry=CDateTimeTool.dateAdd(new Date(), 0, 0, -day);
			String dateTime=CDateTimeTool.formatDateTime(expiry,"yyyy-MM-dd");
			List<UserCart> list = ucUtils.queryExpireNoBuildOrder(dateTime);
			if(list.size()==0) {
				return;
			}

			for(UserCart uc:list){
				CloudContextUtils.setAgentId(uc.getAgentId());
				//删除到期未生成订单
				int ret=ucUtils.delUserCart(uc.getCartNo());
				if(ret>0){
					UserLogUtils.addLog(this, 1000, "delCartNoBuildOrder", "系统自动任务：删除购物车到期未生成订单，购物车号【"+uc.getCartNo()+"】，加入购物车时间【"+uc.getCartTime()+"】");
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
			StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            SysRunTimeLogUtils.addLog(this, 1000, "delCartNoBuildOrder", "删除购物车中未生成订单任务，异常=【"+e.getMessage()+"】");
		}
	}
}
